from flask import Blueprint, request
from flask_cors import CORS

from py.Services.AnnouncementService import *
from py.commonResponse.CommonResponse import *
from py.commonResponse.Dict import Dict

bp_an = Blueprint('announcement', __name__, url_prefix="/announcements")  # 蓝图使用方法，参数里给定文件名，还可以给定url前缀


# 增加公告
@bp_an.route('', methods=['POST'])
def addAnnouncement():
    announce = request.json
    msg = AnnouncementService.Announcement_Insert(Dict(announce))
    return createForSuccessWM(msg)


# 获取所有公告
@bp_an.route('', methods=['GET'])
def getAllAnnouncement():
    announcementList = AnnouncementService.Announcement_Query_All()
    announcementList1 = []
    for announcement in announcementList:
        announcement.date = announcement.date.strftime('%Y-%m-%d')
        announcementList1.append(dict(announcement))
    if not announcementList1:
        return createForSuccessWM("没有任何公告")
    return createForSuccessWMD('查找成功', announcementList1)


# 通过日期获取公告
@bp_an.route('<string:date_str>', methods=['GET'])
def getAllAnnouncementByDate(date_str):
    date = datetime.strptime(date_str, '%Y-%m-%d')
    announcementList = AnnouncementService.Announcement_Query_ByDate(date)
    announcementList1 = []
    for announcement in announcementList:
        announcementList1.append(dict(announcement))
    if not announcementList1:
        return createForSuccessWM("这一天没有任何公告")
    return createForSuccessWMD('查找成功', announcementList1)


# 删除date之前的所有公告
@bp_an.route('<string:date_str>', methods=['DELETE'])
def deleteAnnouncement(date_str):
    date = datetime.strptime(date_str, '%Y-%m-%d')
    AnnouncementService.Announcement_Delete_ByDate(date)
    return createForSuccessWM('删除成功')


# 修改公告
@bp_an.route('', methods=['PUT'])
def updateAnnouncement():
    announcement = request.json
    msg = AnnouncementService.Announcement_Update((Dict(announcement)))

    return createForSuccessWM(msg)


# 删除已经存在超过day天的消息
@bp_an.route('<int:day>', methods=['DELETE'])
def deleteAnnouncementByDay(day):
    msg = AnnouncementService.Announcement_Delete_ByDuration(day)
    return createForSuccessWM(msg)


# 通过id删除公告
@bp_an.route('id/<int:id>', methods=['DELETE'])
def announcement_Delete_ByID(id):
    msg = AnnouncementService.Announcement_Delete_ByID(id)
    return createForSuccessWM(msg)
